#include "drv_tim_16b.h"
#include "drv_sysclk.h"
#include "drv_led.h"
#include <mm32f327xx_hal_config.h>

TIM_16B_Init_Type htim;

static void Drv_PWM_GPIO_Init(void)
{
    PWM_GPIO_CLK_EN();
    
    GPIO_Init_Type gpio_init;
    /* PC6 - TIM3_CH1. */
    gpio_init.Pins      = PWM_PIN;
    gpio_init.PinMode   = GPIO_PinMode_AF_PushPull;
    gpio_init.Speed     = GPIO_Speed_50MHz;
    GPIO_Init(PWM_PORT, &gpio_init);
    GPIO_PinAFConf(PWM_PORT, gpio_init.Pins, GPIO_AF_2);
}

static void Drv_TIM_16B_Init(void)
{
    /* Set the counter counting step. */
    TIM_CLK_EN();
    
    htim.ClockFreqHz            = HAL_GetSysClockFreq();
    htim.StepFreqHz             = 1000; /* set the step. */
    htim.Period                 = 1000 - 1u; /* set the period. */
    htim.EnablePreloadPeriod    = false;
    htim.PeriodMode             = TIM_16B_PeriodMode_Continuous;  /* continus mode */
    htim.CountMode              = TIM_16B_CountMode_Increasing;
    TIM_16B_Init(TIM_PORT, &htim);

    /* Set the PWM output channel. */
    TIM_16B_OutputCompareConf_Type tim_outcomp_conf;
    tim_outcomp_conf.ChannelValue               = 0u;   /* duty */
    tim_outcomp_conf.EnableFastOutput           = false;
    tim_outcomp_conf.EnablePreLoadChannelValue  = false; /* Disable preload, put data immediately. */
    tim_outcomp_conf.RefOutMode                 = TIM_16B_OutputCompareRefOut_FallingEdgeOnMatch;
    tim_outcomp_conf.ClearRefOutOnExtTrigger    = false;
    tim_outcomp_conf.PinPolarity                = TIM_16B_PinPolarity_Rising;
    TIM_16B_EnableOutputCompare(TIM_PORT, PWM_CHANNEL, &tim_outcomp_conf);

    /* Start the counter. */
    TIM_16B_Start(TIM_PORT);
}

void Drv_PWM_Init(void)
{
    Drv_PWM_GPIO_Init();
    Drv_TIM_16B_Init();
    
    TIM_16B_PutChannelValue(TIM_PORT, PWM_CHANNEL, 500);
}